package com.example.controller;

import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.example.common.Re;
import com.example.service.NginxService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;

/**
 * 文件上传和下载
 *
 * @author czx
 * @since 2022/4/30 17:12
 */
@RestController
@RequestMapping("/common")
@Slf4j
public class CommonController {

    @Resource
    NginxService nginxService;

    /**
     * 文件上传
     *
     * @param file 文件
     * @return 结果
     */
    @PostMapping("/upload")
    public Re<String> upload(MultipartFile file) {
        log.info(file.toString());
        String uploadImages = nginxService.uploadImages(file);
        if (StringUtils.isNotEmpty(uploadImages)) {
            return Re.success(uploadImages);
        }
        return Re.error("文件上传失败");
    }

    /*
     * 文件下载
     *
     * @param name     文件名
     * @param response http请求
    @GetMapping("/download")
    public void download(String name, HttpServletResponse response) {

        try {
            //输入流，通过输入流读取文件内容
            FileInputStream fileInputStream = new FileInputStream(basePath + name);

            //输出流，通过输出流将文件写回浏览器，在浏览器展示图片
            ServletOutputStream servletOutputStream = response.getOutputStream();

            response.setContentType("image/jpeg");

            int len;
            byte[] bytes = new byte[1024];
            while ((len = fileInputStream.read(bytes)) != -1) {
                servletOutputStream.write(bytes, 0, len);
                servletOutputStream.flush();
            }

            //关闭资源
            servletOutputStream.close();
            fileInputStream.close();

        } catch (Exception e) {
            e.printStackTrace();
        }
    }*/
}
